package com.cqc.appwidget01;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.widget.RemoteViews;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by cui on 2017/8/7.
 */

public class WidgetService extends Service {

    private Timer timer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();

                RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_appwidget);
                remoteViews.setTextViewText(R.id.tv, format.format(date));
                Intent intent = new Intent();
                intent.setAction("com.cqc.appwidget01.action.UPDATE");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
                remoteViews.setOnClickPendingIntent(R.id.tv, pendingIntent);
                //注意：第二个参数是MyAppWidgetProvider
                ComponentName name = new ComponentName(getPackageName(), "com.cqc.appwidget01.MyAppWidgetProvider");
                AppWidgetManager.getInstance(getBaseContext()).updateAppWidget(name, remoteViews);
            }
        };
        timer.schedule(task, 0, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
